<?php

function http($url, $content, $ispost = 1, $header = [], $verify = false)
{
    $httpInfo = array();
    $ch = curl_init();
    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    //忽略ssl证书
    if ($verify === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    } else {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if (is_array($content)) {
            $params = http_build_query($content);
        }
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);
    if ($response === FALSE) {
        trace("cURL Error: " . curl_errno($ch) . ',' . curl_error($ch), 'error');
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        trace($httpInfo, 'error');
        return false;
    }
    curl_close($ch);
    return $response;
}

/**
 * 生成订单号
 */
function build_orderno(){
    $time = explode(' ', microtime());
    $time2=substr($time['0'],'6','-2');
    return date('YmdHis',time()).$time2.rand(1000,9999);
}
/**
 * @param string $pwd 管理员登录密码
 * @param string $account 管理员账号
 * @return string
 */

function set_pwd($account,$pwd){
    return md5($account.'xycshop'.$pwd);
}


//获取本金加利息
function get_rate_money($money,$rate,$day){
//    本金+本金*利率%*借款天数/365
    return $money+$money*($rate/100)*$day/365;
}

//获取IP 地址
function getIP()
{
    if (isset($_SERVER)) {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $IPaddress = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $IPaddress = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $IPaddress = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $IPaddress = getenv("HTTP_CLIENT_IP");
        } else {
            $IPaddress = getenv("REMOTE_ADDR");
        }
    }

    $IPaddress=explode(',',$IPaddress);//如果出现IP的话，取第一个，因为第二个是代理服务器的IP
    return $IPaddress['0'];
}

/**
 * 添加后台错误登录日志
 * @param $data管理员id
 */
function add_login_error_log($mobile,$content='')
{
    $error_log = M('admin_login_error_log', '', 'XYC');
    $content=empty($content)?'登录失败次数超过3次':$content;
//    $content='登录失败次数超过3次';
    $data = [
        'mobile' => $mobile,
        'content' => $content,
        'ctime' => time(),
        'login_ip'=>getIp()
    ];
    $error_log->add($data);
}


/**
 * 添加管理员登录日志
 * @param string $shop_idenfier 商户号
 * @param string $account 用户账号
 * @param string $name 用户名
 */
function add_login_log($shop_idenfier,$account,$name)
{
    $login_log_db = M('login_log', '', 'XYC');
    $address=get_address(getIP());
    $data = [
        'shop_idenfier' => $shop_idenfier,
        'account' => $account,
        'name' => $name,
        'ip' => getIp(),
        'location' => $address,
        'login_time'=>time()
    ];
    $login_log_db->add($data);
}

function admin_log(){



}

function add_control_log($shop_idenfier,$name,$content,$type='3')
{
    $login_log_db = M('control_log', '', 'XYC');
    $data = [
        'shop_identifier' => $shop_idenfier,
        'name' => $name,
        'content' => $content,
        'type' => $type,
        'ctime'=>time()
    ];
    $login_log_db->add($data);
}

/**
 * 设置隐私
 * @param string $number 号码
 * @param int $type 类型，1手机号，2身份号
 * @return string
 */
function set_privacy($number,$type){
    switch($type){
        case '1':
            return substr($number,0,3).'****'.substr($number,-4);
        case '2':
            return substr($number,0,6).'****'.substr($number,-2);
    }
}

/**
 * 通过ip获取地址
 * @param string $ip ip地址
 * @return mixed
 */
function get_address($ip){
    $url='http://apis.juhe.cn/ip/ip2addr?ip='.$ip.'&dtype=&key=e9c27d80d4eeeba052307682ef10c60b';
    $res=set_curl($url);
    return json_decode($res,true)['result']['area'];
}

/**
 * 添加推送/发送信息日志
 * @param string $vid 用户唯一标示
 * @param string $content 推送/发送内容
 * @param string $title 推送/发送标题
 * @param string $type 类型，1个人，2群体
 */
function add_news($vid='0', $content, $type='1',$title='')
{
    $info = M('user_news','','USER');
    $data['vid'] = $vid;
    $data['title'] = empty($title)?'系统信息':$title;
    $data['content'] = $content;
    $data['ctime'] = time();
    $data['type'] = $type;
    $info->add($data);
}


/**
 * @param string $vid
 * @param float $money 退还金额
 * @param string $type 类型，1、退还贷后服务费，2、退还部分利息
 */
function add_balance_log($vid,$money,$type){
    $balance_db=M('balance_log','','CAIWU');
    $data['vid']=$vid;
    $data['money']=$money;
    $data['type']=$type;
    $data['ctime']=time();
    $balance_db->add($data);
}


function add_down_data_log($aid,$content){
    $logmodel = M('down_data_log', '', 'USER');
    if (empty($content)) {
        $content = "在ip为:" . getIP() . "登录。";
    }
    $data = [
        'aid' => $aid,
        'content' => $content,
        'ctime' => time()
    ];
    $logmodel->add($data);
}

/**
 * 递归获取无限级分类
 */
function get_new_array($data = array(), $pre_openid = '', $arrs = array())
{
    static $arr = array();
    if (!empty($arrs)) {
        for ($i = 0; $i < count($arrs); $i++) {
            array_shift($arr);
        }
    }else{
        $pre_openid = empty($pre_openid) ? '0' : $pre_openid;
        foreach ($data as $key => $value) {
            if ($value['pre_openid'] == $pre_openid) {
                $arr[] = $value;
                get_new_array($data, $value['openid']);
            }
        }
        return $arr;
    }

}

/**
 * 获取该用户的所有上级
 */
//static $a;
function get_all_pre($data = array(), $openid = '')
{

    static $parr;
    foreach ($data as $key => $value) {
        if ($value['openid'] == $openid) {
            $parr[] = $value;
            get_all_pre($data, $value['pre_openid']);
        }
    }
    return $parr;
}


/**
 * 递归获取无限级分类(后台权限添加使用)
 */
function get_new_arrays($data = array(), $pid = '', $arrs = array())
{
    static $arrss = array();
    if (!empty($arrs)) {
        for ($i = 0; $i < count($arrs); $i++) {
            array_shift($arrss);
        }
    }
    $pid = empty($pid) ? '0' : $pid;
    foreach ($data as $key => $value) {
        if ($value['pid'] == $pid) {
            $arrss[] = $value;
            get_new_arrays($data, $value['id']);
        }
    }
    return $arrss;
}

/**
 * 记录管理员行为轨迹
 * @param string $name 管理员名称
 * @param string $content 访问内容
 */
function add_admin_behavior($name,$content){
    $data['name']=$name;
    $data['content']=$content;
    $data['ctime']=time();
    M('adm_behavior','','USER')->add($data);
}

function set_curl($url, $data = array(), $header = '')
{
    $ch = curl_init();
    if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
    curl_setopt($ch, CURLOPT_URL, $url);
    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_POST, '1');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //禁用后cURL将终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    if (curl_error($ch)) {
        return '错误信息:' . curl_error($ch);
    }
    curl_close($ch);
    return $res;
}

//测试程序执行时间使用
function get_microtime()
{
    $time = explode(' ', microtime());
    return $time['1'] + $time['0'];
}

//获取星期时间
function get_weekday($time){
    $day=array('日','一','二','三','四','五','六');
    return '星期'.$day[date('w',$time)];
}

function removexss($val){
    static $obj=null;
    if($obj===null){
        include('./Public/htmlpurifier/HTMLPurifier.includes.php');
        $config=HTMLpurifier_Config::createDefault();
        $config->set('HTML.TargetBlank',TRUE);
        $obj=new HTMLPurifier($config);
    }
    return $obj->purify($val);
}

